﻿using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Windows.Forms;
using System.Threading.Tasks;
using DevExpress.XtraSplashScreen;
using DevExpress.XtraEditors;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using prjKQXS_UI.CSDL;
using prjKQXS_UI.Danh_muc;
using prjKQXS_UI.Doanh_thu;
using prjKQXS_UI.Hop_dong;
using prjKQXS_UI.Truyen_thong;
using prjKQXS_UI.Security;
using prjKQXS_DLL;
using prjKQXS_DLL.CSDL;
using prjKQXS_UI.Lo_to;
using prjKQXS_UI.Boc;

namespace prjKQXS_UI.View
{
    public partial class frmMain : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        SqlConnection conn = new SqlConnection(BienTc.connString);

        //Biến này để kiểm tra khi xảy ra event formClosing, nếu đang thêm mới/sửa dữ liệu dở dang thì hỏi trước khi đóng.
        //- Khi không có form nào đang thêm mới/sửa dữ liệu dở dang thì sEdittingFormName="";
        //- Ngược lại thì sEdittingFormName chứa tên các form đang thêm mới/sửa dữ liệu dở dang
        public static string sEdittingFormName = "";

        //3 biến sau để cài đặt hiển thị màu cho gridView trong các trường hợp tại các form.
        public static Color InvalidExceptionColor = Color.Gold;
        public static Color lockColor = Color.Brown;
        public static Color unLockColor = Color.Black;

        #region form's event =========================================================
        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            lblFullName.Caption = BienTc.FullName;
            lblNgayLV.Caption = DateTime.Now.ToString("dd/MM/yyyy");
            this.WindowState = FormWindowState.Maximized;
            frmMetro frm = new frmMetro(this);
            frm.MdiParent = this;
            frm.WindowState = FormWindowState.Maximized;
            frm.Show();
            PhanQuyenMenu();
            Task.Factory.StartNew(() => clsCommon.autoBackup());
            reDesign();
            rpTheChap.Visible = false;
        }

        string serverConnectionString = "";
        private void frmMain_Shown(object sender, EventArgs e)
        {
            // lay ngay tu server http://nist.time.gov/actualtime.cgi?lzbc=siqm9b
            Task tsk = new Task(() =>
            {
                try
                {
                    BienTc.currentDate = clsCommon.GetNistTimeNew();
                }
                catch
                {
                    //clsCommon.MsgBox("Không có kết nối internet, bạn sẽ không sử dụng được một số chức năng.", 5);
                    BienTc.currentDate = DateTime.MinValue;
                }
            });
            tsk.Start();clsThietLapLai tll = new clsThietLapLai();
            tll.OnAction += new clsThietLapLai.OnActionHandler(tll_OnAction);
            tll.OnError += new clsThietLapLai.OnErrorHandler(tll_OnError);

            tll.autoTLLX(1);
            tll.autoTLLX(2);

            if (BienTc.isQuanHuyen)
            {
                DialogResult dlgResult = clsCommon.MsgBox("Bạn có muốn cập nhật thông tin từ máy chủ công ty hay không?", 6);
                if (dlgResult == System.Windows.Forms.DialogResult.Yes)
                {
                    SplashScreenManager.ShowForm(typeof(frmWaitForm));
                    try
                    {
                        serverConnectionString = clsCommon.getServerConnectionString();

                        CapNhat_DMHOIDONG();
                        CapNhat_DMDONVI();
                        CapNhat_DMCANBO();CapNhat_HOPDONG();
                        CapNhat_NhatKyChuyenDL();

                        clsCommon.MsgBox("Cập nhật thành công!", 1);
                    }
                    catch
                    {
                        clsCommon.MsgBox("Cập nhật không thành công!", 5);
                    }
                    finally
                    {
                        SplashScreenManager.CloseForm();
                    }
                }
            }

            //tsk.Wait();
        }


        #region CẬP NHẬT BẢNG DMHOIDONG, DMDONVI, DMCANBO, HOPDONG =================
        private void CapNhat_DMHOIDONG()
        {
            SqlConnection connClient = new SqlConnection(BienTc.connString);
            SqlConnection connServer = new SqlConnection(serverConnectionString);
            connClient.Open();
            connServer.Open();

            //Thực hiện cập nhật
            string sql = "SELECT * FROM DMHOIDONG WHERE isPublic = 1";
            SqlCommand cmd = new SqlCommand(sql, connServer);
            DataTable dt = clsCommon.FillData(sql, connServer);

            sql = "UPDATE DMHOIDONG SET isPublic = 0";
            cmd = new SqlCommand(sql, connClient);
            cmd.ExecuteNonQuery();

            foreach (DataRow dr in dt.Rows)
            {
                sql = "SELECT COUNT(ID) FROM DMHOIDONG WHERE ID = @HoiDongID";
                cmd = new SqlCommand(sql, connClient);
                cmd.Parameters.AddWithValue("@HoiDongID", dr["ID"]);

                if (cmd.ExecuteScalar().ToString().Trim() == "0")
                {
                    //Thực hiện Insert những ID chưa có
                    sql = @"SET IDENTITY_INSERT dbo.DMHOIDONG ON
                                INSERT DMHOIDONG(ID, Mahoidong, Tenhoidong, Chucvu, SDT, isPublic)
                                    VALUES (@ID, @Mahoidong, @Tenhoidong, @Chucvu, @SDT, 1)";
                    cmd = new SqlCommand(sql, connClient);
                    cmd.Parameters.AddWithValue("@ID", dr["ID"]);
                    cmd.Parameters.AddWithValue("@Mahoidong", dr["Mahoidong"]);
                    cmd.Parameters.AddWithValue("@Tenhoidong", dr["Tenhoidong"]);
                    cmd.Parameters.AddWithValue("@Chucvu", dr["Chucvu"]);
                    cmd.Parameters.AddWithValue("@SDT", dr["SDT"]);
                    cmd.ExecuteNonQuery();
                }
                else
                {
                    //Thực hiện update những ID đã có
                    sql = @"UPDATE DMHOIDONG
                            SET Mahoidong = @Mahoidong
                                , Tenhoidong = @Tenhoidong
                                , Chucvu = @Chucvu
                                , SDT = @SDT
                                , isPublic = 1
                            WHERE ID = @ID";
                    cmd = new SqlCommand(sql, connClient);
                    cmd.Parameters.AddWithValue("@ID", dr["ID"]);
                    cmd.Parameters.AddWithValue("@Mahoidong", dr["Mahoidong"]);
                    cmd.Parameters.AddWithValue("@Tenhoidong", dr["Tenhoidong"]);
                    cmd.Parameters.AddWithValue("@Chucvu", dr["Chucvu"]);
                    cmd.Parameters.AddWithValue("@SDT", dr["SDT"]);
                    cmd.ExecuteNonQuery();
                }
            }

            try
            {
                //Thực hiện xóa những ID đã xóa trên server
                sql = @"DELETE DMHOIDONG WHERE isPublic = 0";
                cmd = new SqlCommand(sql, connClient);
                cmd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                cls_OnAction(ex, "DMHOIDONG");
            }
            catch (Exception ex)
            {
                cls_OnError(ex);
            }
        }

        private void CapNhat_DMDONVI()
        {
            SqlConnection connClient = new SqlConnection(BienTc.connString);
            SqlConnection connServer = new SqlConnection(serverConnectionString);
            connClient.Open();
            connServer.Open();

            //Thực hiện cập nhật
            string sql = "SELECT * FROM DMDONVI WHERE isPublic = 1";
            SqlCommand cmd = new SqlCommand(sql, connServer);
            DataTable dt = clsCommon.FillData(sql, connServer);

            sql = "UPDATE DMDONVI SET isPublic = 0";
            cmd = new SqlCommand(sql, connClient);
            cmd.ExecuteNonQuery();

            foreach (DataRow dr in dt.Rows)
            {
                sql = "SELECT COUNT(Ma_DT) FROM DMDONVI WHERE Ma_DT = @MaDV";
                cmd = new SqlCommand(sql, connClient);
                cmd.Parameters.AddWithValue("@MaDV", dr["Ma_DT"]);
                if (cmd.ExecuteScalar().ToString().Trim() == "0")
                {
                    //Thực hiện Insert những đơn vị chưa có
                    sql = @"SET IDENTITY_INSERT dbo.DMDONVI ON
                                INSERT DMDONVI(Ma_DT, Ten_DT, Giam_Doc, SDT, FAX, Dia_Chi, isPublic)
                                    VALUES (@Ma_DT, @Ten_DT, @Giam_Doc, @SDT, @FAX, @Dia_Chi, 1)";
                    cmd = new SqlCommand(sql, connClient);
                    cmd.Parameters.AddWithValue("@Ma_DT", dr["Ma_DT"]);
                    cmd.Parameters.AddWithValue("@Ten_DT", dr["Ten_DT"]);
                    cmd.Parameters.AddWithValue("@Giam_Doc", dr["Giam_Doc"]);
                    cmd.Parameters.AddWithValue("@SDT", dr["SDT"]);
                    cmd.Parameters.AddWithValue("@FAX", dr["FAX"]);
                    cmd.Parameters.AddWithValue("@Dia_Chi", dr["Dia_Chi"]);
                    cmd.ExecuteNonQuery();
                }
                else
                {
                    //Thực hiện update những đơn vị đã có
                    sql = @"UPDATE DMDONVI
                                SET Ten_DT = @Ten_DT
                                    , Giam_Doc = @Giam_Doc
                                    , SDT = @SDT
                                    , FAX = @FAX
                                    , Dia_Chi = @Dia_Chi
                                    , isPublic = 1
                                WHERE Ma_DT = @MaDV";
                    cmd = new SqlCommand(sql, connClient);
                    cmd.Parameters.AddWithValue("@MaDV", dr["Ma_DT"]);
                    cmd.Parameters.AddWithValue("@Ten_DT", dr["Ten_DT"]);
                    cmd.Parameters.AddWithValue("@Giam_Doc", dr["Giam_Doc"]);
                    cmd.Parameters.AddWithValue("@SDT", dr["SDT"]);
                    cmd.Parameters.AddWithValue("@FAX", dr["FAX"]);
                    cmd.Parameters.AddWithValue("@Dia_Chi", dr["Dia_Chi"]);
                    cmd.ExecuteNonQuery();
                }
            }

            try
            {
                //Thực hiện xóa những ID đã xóa trên server
                sql = @"DELETE DMDONVI WHERE isPublic = 0";
                cmd = new SqlCommand(sql, connClient);
                cmd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                cls_OnAction(ex, "DMDONVI");
            }
            catch (Exception ex)
            {
                cls_OnError(ex);
            }
        }

        private void CapNhat_DMCANBO()
        {
            SqlConnection connClient = new SqlConnection(BienTc.connString);
            SqlConnection connServer = new SqlConnection(serverConnectionString);
            connClient.Open();
            connServer.Open();

            //Thực hiện cập nhật
            string sql = "SELECT * FROM DMCANBO WHERE isPublic = 1";
            SqlCommand cmd = new SqlCommand(sql, connServer);
            DataTable dt = clsCommon.FillData(sql, connServer);

            sql = "UPDATE DMCANBO SET isPublic = 0";
            cmd = new SqlCommand(sql, connClient);
            cmd.ExecuteNonQuery();

            foreach (DataRow dr in dt.Rows)
            {
                sql = "SELECT COUNT(ID) FROM DMCANBO WHERE ID = @ID";
                cmd = new SqlCommand(sql, connClient);
                cmd.Parameters.AddWithValue("@ID", dr["ID"]);
                if (cmd.ExecuteScalar().ToString().Trim() == "0")
                {
                    //Thực hiện Insert những ID chưa có
                    sql = @"SET IDENTITY_INSERT dbo.DMCANBO ON
                                INSERT DMCANBO 
	                            (
                                    ID		                            
                                    , Ma_DT
		                            , Ten_DT
		                            , SDT
		                            , Ma_DMChucVu
		                            , Ma_DMDonVi
		                            , Noi_O
		                            , SoHD
		                            , NgayHD
		                            , MST
		                            , CMT
		                            , Noi_Cap
		                            , Ngay_Cap
		                            , Tuyen
		                            , isBanRong
		                            , Tien_Goc
		                            , KeHoachGiao
		                            , isPublic
	                            )
	                            VALUES 
	                            (
                                    @ID
		                            , @Ma_DT
		                            , @Ten_DT
		                            , @SDT
		                            , @Ma_DMChucVu
		                            , @Ma_DMDonVi
		                            , @Noi_O
		                            , @SoHD
		                            , @NgayHD
		                            , @MST
		                            , @CMT
		                            , @Noi_Cap
		                            , @Ngay_Cap
		                            , @Tuyen
		                            , @isBanRong
		                            , @Tien_Goc
		                            , @KeHoachGiao
		                            , 1
	                            )
                            ";
                    cmd = new SqlCommand(sql, connClient);
                    cmd.Parameters.AddWithValue("@ID", dr["ID"]);
                    cmd.Parameters.AddWithValue("@Ma_DT", dr["Ma_DT"].ToString().Trim().ToUpper());
                    cmd.Parameters.AddWithValue("@Ten_DT", dr["Ten_DT"]);
                    cmd.Parameters.AddWithValue("@SDT", dr["SDT"]);
                    cmd.Parameters.AddWithValue("@Ma_DMChucVu", dr["Ma_DMChucVu"]);
                    cmd.Parameters.AddWithValue("@Ma_DMDonVi", dr["Ma_DMDonVi"]);
                    cmd.Parameters.AddWithValue("@SoHD", dr["SoHD"]);
                    cmd.Parameters.AddWithValue("@NgayHD", dr["NgayHD"]);
                    cmd.Parameters.AddWithValue("@Noi_O", dr["Noi_O"]);
                    cmd.Parameters.AddWithValue("@MST", dr["MST"]);
                    cmd.Parameters.AddWithValue("@CMT", dr["CMT"]);
                    cmd.Parameters.AddWithValue("@Noi_Cap", dr["Noi_Cap"]);
                    cmd.Parameters.AddWithValue("@Ngay_Cap", dr["Ngay_Cap"]);
                    cmd.Parameters.AddWithValue("@Tuyen", dr["Tuyen"]);
                    cmd.Parameters.AddWithValue("@isBanRong", dr["isBanRong"]);
                    cmd.Parameters.AddWithValue("@Tien_Goc", dr["Tien_Goc"]);
                    cmd.Parameters.AddWithValue("@Ngay_ThanhLy", dr["Ngay_ThanhLy"]);
                    cmd.Parameters.AddWithValue("@Ly_Do", dr["Ly_Do"]);
                    cmd.Parameters.AddWithValue("@KeHoachGiao", dr["KeHoachGiao"]);
                    cmd.ExecuteNonQuery();
                }
                else
                {
                    //Thực hiện update những ID đã có
                    sql = @"UPDATE DMCANBO 
	                            SET Ma_DT			= @Ma_DT
		                            , Ten_DT		= @Ten_DT
		                            , SDT			= @SDT
		                            , Ma_DMChucVu	= @Ma_DMChucVu
		                            , Noi_O			= @Noi_O
		                            , SoHD			= @SoHD
		                            , NgayHD		= @NgayHD
		                            , MST			= @MST
		                            , CMT			= @CMT
		                            , Noi_Cap		= @Noi_Cap
		                            , Ngay_Cap		= @Ngay_Cap
		                            , Tuyen			= @Tuyen
		                            , isBanRong		= @isBanRong
		                            , Tien_Goc		= @Tien_Goc
		                            , KeHoachGiao	= @KeHoachGiao
		                            , Ngay_ThanhLy	= @Ngay_ThanhLy
		                            , Ly_Do			= @Ly_Do
                                    , isPublic      = 1
	                            WHERE ID = @ID";
                    cmd = new SqlCommand(sql, connClient);
                    cmd.Parameters.AddWithValue("@ID", dr["ID"]);
                    cmd.Parameters.AddWithValue("@Ma_DT", dr["Ma_DT"].ToString().Trim().ToUpper());
                    cmd.Parameters.AddWithValue("@Ten_DT", dr["Ten_DT"]);
                    cmd.Parameters.AddWithValue("@SDT", dr["SDT"]);
                    cmd.Parameters.AddWithValue("@Ma_DMChucVu", dr["Ma_DMChucVu"]);
                    cmd.Parameters.AddWithValue("@Ma_DMDonVi", dr["Ma_DMDonVi"]);
                    cmd.Parameters.AddWithValue("@SoHD", dr["SoHD"]);
                    cmd.Parameters.AddWithValue("@NgayHD", dr["NgayHD"]);
                    cmd.Parameters.AddWithValue("@Noi_O", dr["Noi_O"]);
                    cmd.Parameters.AddWithValue("@MST", dr["MST"]);
                    cmd.Parameters.AddWithValue("@CMT", dr["CMT"]);
                    cmd.Parameters.AddWithValue("@Noi_Cap", dr["Noi_Cap"]);
                    cmd.Parameters.AddWithValue("@Ngay_Cap", dr["Ngay_Cap"]);
                    cmd.Parameters.AddWithValue("@Tuyen", dr["Tuyen"]);
                    cmd.Parameters.AddWithValue("@isBanRong", dr["isBanRong"]);
                    cmd.Parameters.AddWithValue("@Tien_Goc", dr["Tien_Goc"]);
                    cmd.Parameters.AddWithValue("@KeHoachGiao", dr["KeHoachGiao"]);
                    cmd.Parameters.AddWithValue("@Ngay_ThanhLy", dr["Ngay_ThanhLy"]);
                    cmd.Parameters.AddWithValue("@Ly_Do", dr["Ly_Do"]);
                    cmd.ExecuteNonQuery();
                }
            }

            try
            {
                //Thực hiện xóa những ID đã xóa trên server
                sql = @"DELETE DMCANBO WHERE isPublic = 0";
                cmd = new SqlCommand(sql, connClient);
                cmd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                cls_OnAction(ex, "DMCANBO");
            }
            catch (Exception ex)
            {
                cls_OnError(ex);
            }

        }

        private void CapNhat_HOPDONG()
        {
            SqlConnection connClient = new SqlConnection(BienTc.connString);
            SqlConnection connServer = new SqlConnection(serverConnectionString);
            connClient.Open();
            connServer.Open();

            //Thực hiện cập nhật
            string sql = "SELECT * FROM HOPDONG WHERE isPublic = 1";
            SqlCommand cmd = new SqlCommand(sql, connServer);
            DataTable dt = clsCommon.FillData(sql, connServer);

            sql = "UPDATE HOPDONG SET isPublic = 0";
            cmd = new SqlCommand(sql, connClient);
            cmd.ExecuteNonQuery();

            foreach (DataRow dr in dt.Rows)
            {
                sql = "SELECT COUNT(ID) FROM HOPDONG WHERE ID = @ID";
                cmd = new SqlCommand(sql, connClient);
                cmd.Parameters.AddWithValue("@ID", dr["ID"]);
                if (cmd.ExecuteScalar().ToString().Trim() == "0")
                {
                    //Thực hiện Insert những ID chưa có
                    sql = @"SET IDENTITY_INSERT dbo.HOPDONG ON
                                INSERT HOPDONG
                                (
                                    ID
		                            , Ma_DT
		                            , Ngay_HD
		                            , Ma_DaiLy
		                            , Ten_DaiLy
		                            , DMCanBoID
		                            , Noi_O
		                            , MST
		                            , CMT
		                            , Noi_Cap
		                            , Ngay_Cap
		                            , Noi_Ban
		                            , Ngay_Ban
		                            , So_Tien
		                            , Ma_DMTinhTrang
		                            , Ma_DMLoaiHD
		                            , Ngay_ThanhLy
		                            , Ly_Do
		                            , isTT
                                )
	                            VALUES
                                (
                                    @ID
		                            , @Ma_DT
		                            , @Ngay_HD
		                            , @Ma_DaiLy
		                            , @Ten_DaiLy
		                            , @DMCanBoID
		                            , @Noi_O
		                            , @MST
		                            , @CMT
		                            , @Noi_Cap
		                            , @Ngay_Cap
		                            , @Noi_Ban
		                            , @Ngay_Ban
		                            , @So_Tien
		                            , @Ma_DMTinhTrang
		                            , @Ma_DMLoaiHD
		                            , @Ngay_ThanhLy
		                            , @Ly_Do
		                            , @isTT
                                )";
                    cmd = new SqlCommand(sql, connClient);
                    cmd.Parameters.AddWithValue("@ID", dr["ID"]);
                    cmd.Parameters.AddWithValue("@Ma_DT", dr["Ma_DT"]);
                    cmd.Parameters.AddWithValue("@Ngay_HD", dr["Ngay_HD"]);
                    cmd.Parameters.AddWithValue("@Ma_DaiLy", dr["Ma_DaiLy"]);
                    cmd.Parameters.AddWithValue("@Ten_DaiLy", dr["Ten_DaiLy"]);
                    cmd.Parameters.AddWithValue("@DMCanBoID", dr["DMCanBoID"]);
                    cmd.Parameters.AddWithValue("@Noi_O", dr["Noi_O"]);
                    cmd.Parameters.AddWithValue("@MST", dr["MST"]);
                    cmd.Parameters.AddWithValue("@CMT", dr["CMT"]);
                    cmd.Parameters.AddWithValue("@Noi_Cap", dr["Noi_Cap"]);
                    cmd.Parameters.AddWithValue("@Ngay_Cap", dr["Ngay_Cap"]);
                    cmd.Parameters.AddWithValue("@Noi_Ban", dr["Noi_Ban"]);
                    cmd.Parameters.AddWithValue("@Ngay_Ban", dr["Ngay_Ban"]);
                    cmd.Parameters.AddWithValue("@So_Tien", dr["So_Tien"]);
                    cmd.Parameters.AddWithValue("@Ma_DMTinhTrang", dr["Ma_DMTinhTrang"]);
                    cmd.Parameters.AddWithValue("@Ma_DMLoaiHD", dr["Ma_DMLoaiHD"]);
                    cmd.Parameters.AddWithValue("@Ngay_ThanhLy", dr["Ngay_ThanhLy"]);
                    cmd.Parameters.AddWithValue("@Ly_Do", dr["Ly_Do"]);
                    cmd.Parameters.AddWithValue("@isTT", dr["isTT"]);
                    cmd.ExecuteNonQuery();
                }
                else
                {
                    //Thực hiện update những ID đã có
                    sql = @"UPDATE HOPDONG 
	                            SET Ma_DT = @Ma_DT
	                                , Ngay_HD = @Ngay_HD
	                                , Ma_DaiLy = @Ma_DaiLy
	                                , Ten_DaiLy = @Ten_DaiLy
	                                , Noi_O = @Noi_O
	                                , MST = @MST
	                                , CMT = @CMT
	                                , Noi_Cap = @Noi_Cap
	                                , Ngay_Cap = @Ngay_Cap
	                                , Noi_Ban = @Noi_Ban
	                                , Ngay_Ban = @Ngay_Ban
	                                , So_Tien = @So_Tien
	                                , Ma_DMTinhTrang = @Ma_DMTinhTrang
	                                , Ma_DMLoaiHD = @Ma_DMLoaiHD
	                                , Ngay_ThanhLy = @Ngay_ThanhLy
	                                , Ly_Do = @Ly_Do
	                                , isTT = @isTT
                                    , isPublic = 1
	                            WHERE ID = @ID";
                    cmd = new SqlCommand(sql, connClient);
                    cmd.Parameters.AddWithValue("@ID", dr["ID"]);
                    cmd.Parameters.AddWithValue("@Ma_DT", dr["Ma_DT"]);
                    cmd.Parameters.AddWithValue("@Ngay_HD", dr["Ngay_HD"]);
                    cmd.Parameters.AddWithValue("@Ma_DaiLy", dr["Ma_DaiLy"]);
                    cmd.Parameters.AddWithValue("@Ten_DaiLy", dr["Ten_DaiLy"]);
                    cmd.Parameters.AddWithValue("@DMCanBoID", dr["DMCanBoID"]);
                    cmd.Parameters.AddWithValue("@Noi_O", dr["Noi_O"]);
                    cmd.Parameters.AddWithValue("@MST", dr["MST"]);
                    cmd.Parameters.AddWithValue("@CMT", dr["CMT"]);
                    cmd.Parameters.AddWithValue("@Noi_Cap", dr["Noi_Cap"]);
                    cmd.Parameters.AddWithValue("@Ngay_Cap", dr["Ngay_Cap"]);
                    cmd.Parameters.AddWithValue("@Noi_Ban", dr["Noi_Ban"]);
                    cmd.Parameters.AddWithValue("@Ngay_Ban", dr["Ngay_Ban"]);
                    cmd.Parameters.AddWithValue("@So_Tien", dr["So_Tien"]);
                    cmd.Parameters.AddWithValue("@Ma_DMTinhTrang", dr["Ma_DMTinhTrang"]);
                    cmd.Parameters.AddWithValue("@Ma_DMLoaiHD", dr["Ma_DMLoaiHD"]);
                    cmd.Parameters.AddWithValue("@Ngay_ThanhLy", dr["Ngay_ThanhLy"]);
                    cmd.Parameters.AddWithValue("@Ly_Do", dr["Ly_Do"]);
                    cmd.Parameters.AddWithValue("@isTT", dr["isTT"]);
                    cmd.ExecuteNonQuery();
                }
            }

            try
            {
                //Thực hiện xóa những ID đã xóa trên server
                sql = @"DELETE HOPDONG WHERE isPublic = 0";
                cmd = new SqlCommand(sql, connClient);
                cmd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                cls_OnAction(ex, "HOPDONG");
            }
            catch (Exception ex)
            {
                cls_OnError(ex);
            }
        }
        private void CapNhat_NhatKyChuyenDL()
        {
            SqlConnection connClient = new SqlConnection(BienTc.connString);
            SqlConnection connServer = new SqlConnection(serverConnectionString);
            connClient.Open();
            connServer.Open();

            //Thực hiện cập nhật
            string sql = "SELECT * FROM tblChuyenDL WHERE isPublic=1";
            SqlCommand cmd = new SqlCommand(sql, connServer);
            DataTable dt = clsCommon.FillData(sql, connServer);

            sql = "UPDATE tblChuyenDL SET isPublic = 0";
            cmd = new SqlCommand(sql, connClient);
            cmd.ExecuteNonQuery();

            foreach (DataRow dr in dt.Rows)
            {
                sql = "SELECT COUNT(ID) FROM tblChuyenDL WHERE ID = @ID";
                cmd = new SqlCommand(sql, connClient);
                cmd.Parameters.AddWithValue("@ID", dr["ID"]);
                if (cmd.ExecuteScalar().ToString().Trim() == "0")
                {
                     //Thực hiện Insert những ID chưa có
                    sql = @"SET IDENTITY_INSERT dbo.tblChuyenDL ON
                        INSERT tblChuyenDL
                        (
                              ID
                             ,Ngay
                             ,HopDongID
                             ,DMCanBoID
                             ,MaDLMoi
                             ,isPublic
                        )
                       VALUES
                        ( 
                               @ID
                             , @Ngay
                             , @HopDongID
                             , @DMCanBoID
                             , @MaDLMoi
                             , 1

                         )
                       ";
                    cmd = new SqlCommand(sql, connClient);
                    cmd.Parameters.AddWithValue("@ID", dr["ID"]);
                    cmd.Parameters.AddWithValue("@Ngay", dr["Ngay"]);
                    cmd.Parameters.AddWithValue("@HopDongID", dr["HopDongID"]);
                    cmd.Parameters.AddWithValue("@DMCanBoID", dr["DMCanBoID"]);
                    cmd.Parameters.AddWithValue("@MaDLMoi", dr["MaDLMoi"]);
                    cmd.ExecuteNonQuery();
                }
                else
                {
                    //Thực hiện update những ID đã có
                    sql = @"UPDATE tblChuyenDL
                          SET Ngay = @Ngay
                            , HopDongID = @HopDongID
                            , DMCanBoID = @DMCanBoID
                            , MaDLMoi = @MaDLMoi
                            , isPublic = 1
                            WHERE ID = @ID";
                    cmd = new SqlCommand(sql, connClient);
                    cmd.Parameters.AddWithValue("@ID", dr["ID"]);
                    cmd.Parameters.AddWithValue("@Ngay", dr["Ngay"]);
                    cmd.Parameters.AddWithValue("@HopDongID", dr["HopDongID"]);
                    cmd.Parameters.AddWithValue("@DMCanBoID", dr["DMCanBoID"]);
                    cmd.Parameters.AddWithValue("@MaDLMoi", dr["MaDLMoi"]);
                    cmd.ExecuteNonQuery();
                }
                try
                {
                    //Thực hiện xoá những ID đã xoá trên Server
                    sql = @"DELETE tblChuyenDL WHERE isPublic = 0";
                    cmd = new SqlCommand(sql, connClient);
                    cmd.ExecuteNonQuery();
                }
                catch (SqlException ex)
                {
                    cls_OnAction(ex, "tblChuyenDL");
                }
                catch (Exception ex)
                {
                    cls_OnError(ex);
                }
                
            }
        }

        #region clsDMCanBo event --------------------------------------------
        private void cls_OnAction(SqlException e, string tableName)
        {
            string msg = "";
            if (tableName == "DMHOIDONG") msg = "DANH MỤC HỘI ĐỒNG";
            else if (tableName == "DMDONVI") msg = "DANH MỤC ĐƠN VỊ";
            else if (tableName == "DMCANBO") msg = "DANH MỤC CÁN BỘ";
            else if (tableName == "HOPDONG") msg = "DANH MỤC HỢP ĐỒNG";

            if (e.Message.Contains("The DELETE statement conflicted with the REFERENCE constraint"))
            {
                XtraMessageBox.Show(msg + " có mẩu tin dư thừa chưa thể xóa vì có dữ liệu ràng buộc liên quan \n(Vui lòng xóa dữ liệu ràng buộc liên quan trước).", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else cls_OnError(e);
        }

        private void cls_OnError(Exception e)
        {
            XtraMessageBox.Show("Một lỗi chưa được xử lý đã xảy ra. Chi tiết lỗi: \n" + e.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            this.Close();
        }
        #endregion ---------------------------------------------------------
        #endregion CẬP NHẬT BẢNG DMHOIDONG, DMDONVI, DMCANBO, HOPDONG ==============


        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (sEdittingFormName.Trim() != "")
            {
                e.Cancel = true;
                string msg = "Bạn chưa thể thoát khỏi chương trình vì đang thực hiện thêm mới hoặc sửa dữ liệu.";
                clsCommon.MsgBox(msg, 5);
            }
            else Application.Exit();
        }
        #endregion ===================================================================


        public void bbiNhatKyQuy_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmQuy frm = new frmQuy();
            if (clsCommon.formIsNotExisting(frm.Name))
            {
                frm.WindowState = FormWindowState.Maximized;
                frm.Show();
            }
            else frm.Dispose();
        }


        #region HỢP ĐỒNG ===============================================================
        private void bbiDMHopDong_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmDMHopDong frm = new frmDMHopDong();
            if (clsCommon.formIsNotExisting(frm.Name))
            {
                frm.MdiParent = this;
                frm.WindowState = FormWindowState.Maximized;
                frm.Show();
            }
            else frm.Dispose();
        }

        private void bbiBaoCaoBienDong_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmBienDongDlyCap2 frm = new frmBienDongDlyCap2("CongTy");
            if (clsCommon.formIsNotExisting(frm.Name))
                frm.ShowDialog();
            else frm.Dispose();
        }
        #endregion HỢP ĐỒNG ============================================================


        #region HOA HỒNG ===============================================================
        public void bbiNhapDoanhThuDaiLy_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmDoanhThu frm = new frmDoanhThu();
            if (clsCommon.formIsNotExisting(frm.Name))
            {
                frm.MdiParent = this;
                frm.WindowState = FormWindowState.Maximized;
                frm.Show();
            }
            else frm.Dispose();
        }

        private void bbiTongHopDT_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmTongHopDT frm = new frmTongHopDT();
            frm.ShowDialog();
        }

        private void bbiTongHopDLyLuuDong_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmDoanhThuLD frm = new frmDoanhThuLD();
            if (clsCommon.formIsNotExisting(frm.Name))
                frm.ShowDialog();
            else frm.Dispose();
        }

        private void bbiRutThuong_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmRutThuong frm = new frmRutThuong();
            frm.ShowDialog();
        }

        #endregion HOA HỒNG ============================================================


        #region THẾ CHẤP ĐẠI LÝ ======================================================
        //Dùng chung cho bbiTheChapDL1, bbiTheChapDL2
        private void bbiTheChapDaiLy_ItemClick(object sender, ItemClickEventArgs e)
        {
            int cap = Convert.ToInt32(e.Item.Name.Substring(e.Item.Name.Length - 1, 1));
            frmDMDLTC frm = new frmDMDLTC(cap);
            if (clsCommon.formIsNotExisting(frm.Name + cap.ToString().Trim()))
            {
                frm.Name = "frmDMDLTC" + cap.ToString().Trim();
                frm.MdiParent = this;
                frm.WindowState = FormWindowState.Maximized;
                frm.Show();
            }
            else frm.Dispose();
        }

        //Dùng chung cho bbiTLLX1, bbiTLLX2
        private void bbiTLLX_ItemClick(object sender, ItemClickEventArgs e)
        {
            int cap = Convert.ToInt32(e.Item.Name.Substring(e.Item.Name.Length - 1, 1));
            frmTLDaiLy frm = new frmTLDaiLy(cap);
            frm.ShowDialog();
        }

        //Dùng chung cho bbiDSNopTC1, bbiDSNopTC2
        private void bbiDSNopTC_ItemClick(object sender, ItemClickEventArgs e)
        {
            int cap = Convert.ToInt32(e.Item.Name.Substring(e.Item.Name.Length - 1, 1));
            prjKQXS_UI.Reports.frmRptBangTheoDoi frm = new prjKQXS_UI.Reports.frmRptBangTheoDoi("Nop", cap);
            frm.ShowDialog();
        }

        //Dùng chung cho bbiTienKyQuy1, bbiTienKyQuy2
        private void bbiTienKyQuy_ItemClick(object sender, ItemClickEventArgs e)
        {
            int cap = Convert.ToInt32(e.Item.Name.Substring(e.Item.Name.Length - 1, 1));
            prjKQXS_UI.Reports.frmRptBangTheoDoi frm = new prjKQXS_UI.Reports.frmRptBangTheoDoi("TienKyQuy", cap);
            frm.ShowDialog();
        }

        //Dùng chung cho bbiRutTienKyQuy1, bbiRutTienKyQuy2
        private void bbiRutTienKyQuy_ItemClick(object sender, ItemClickEventArgs e)
        {
            int cap = Convert.ToInt32(e.Item.Name.Substring(e.Item.Name.Length - 1, 1));
            prjKQXS_UI.Reports.frmRptBangTheoDoi frm = new prjKQXS_UI.Reports.frmRptBangTheoDoi("Rut", cap);
            frm.ShowDialog();
        }

        //Dùng chung cho bbiDanhSachDaiLyTheChap1, bbiDanhSachDaiLyTheChap2
        private void bbiDanhSachDaiLyTheChap_ItemClick(object sender, ItemClickEventArgs e)
        {
            int cap = Convert.ToInt32(e.Item.Name.Substring(e.Item.Name.Length - 1, 1));
            prjKQXS_UI.Reports.frmDaiLyTheChap frm = new prjKQXS_UI.Reports.frmDaiLyTheChap(cap);
            frm.ShowDialog();
        }
        #endregion THẾ CHẤP ĐẠI LÝ ===================================================


        #region TRUYỀN THỐNG ===============================================================
        private void bbiNhapVeNhan_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmTruyenThong_Nhan frm = new frmTruyenThong_Nhan();
            if (clsCommon.formIsNotExisting(frm.Name))
            {
                frm.MdiParent = this;
                frm.WindowState = FormWindowState.Maximized;
                frm.Show();
            }
            else frm.Dispose();
        }

        public void bbiNhapVeHuy_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmNhapVeHuy frm = new frmNhapVeHuy();
            if (clsCommon.formIsNotExisting(frm.Name))
            {
                frm.MdiParent = this;
                frm.WindowState = FormWindowState.Maximized;
                frm.Show();
            }
            else frm.Dispose();
        }

        private void bbiBaoCaoThanhToan_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmBaoCaoThanhToan frm = new frmBaoCaoThanhToan();
            frm.ShowDialog();
        }
        #endregion TRUYỀN THỐNG ============================================================


        #region LÔ TÔ ======================================================================
        public void bbiNhapSoDuThuongLoTo_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmNhapSoDuThuongLoTo frm = new frmNhapSoDuThuongLoTo();
            frm.ShowDialog();

        }
        private void bbiInTongHopDoanhThu_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmInBaocaoTH frm = new frmInBaocaoTH();
            frm.ShowDialog();
        }
        private void btnRutthuong_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmRutThuong frm = new frmRutThuong();
            frm.ShowDialog();
        }
        private void bbiInDT234_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmInDoanhThu234SovaCapso frm = new frmInDoanhThu234SovaCapso();
            frm.ShowDialog();}

        #endregion LÔ TÔ ===================================================================


        #region Other function =============================================================
        private void reDesign()
        {
            //Nếu bbiQuanLyNguoiDung ẩn và bbiDoiMatKhau cũng ẩn thì ẩn rpgQuanTri
            rpgQuanTri.Visible = !(bbiQuanLyNguoiDung.Visibility == BarItemVisibility.Never && bbiDoiMatKhau.Visibility == BarItemVisibility.Never);

            rpTheChap.Visible = rpgTienTheChap.Visible || rpgThietLapLaiXuat.Visible || rpgBangTheoDoiDLTC.Visible || rpgDSDaiLyTheChap.Visible;
            
            if (BienTc.isThanhPho || BienTc.isQuanHuyen)
                bbiBaoCaoBienDong.Caption = "BÁO CÁO BIẾN ĐỘNG ĐẠI LÝ CẤP 2";
            else bbiBaoCaoBienDong.Caption = "BÁO CÁO BIẾN ĐỘNG ĐẠI LÝ TOÀN CÔNG TY";
        }

        private void tll_OnAction(SqlException e)
        {
            tll_OnError(e);
        }

        private void tll_OnError(Exception e)
        {
            XtraMessageBox.Show("Một lỗi chưa được xử lý đã xảy ra. Chi tiết lỗi: \n" + e.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            this.Close();
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.F1)
            {
                frmThongtin frm = new frmThongtin();
                if (clsCommon.formIsNotExisting(frm.Name))
                    frm.ShowDialog();
                else frm.Dispose();
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void PhanQuyenMenu()
        {
            #region HỆ THỐNG
            #region rpgXuLy
            //if (BienTc.isQuanHuyen || !clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiCauHinhMayChu))
                if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiCauHinhMayChu))
            {
                bbiCauHinhMayChu.Visibility = BarItemVisibility.Never;
            }

            //if (BienTc.isThanhPho || BienTc.isQuanHuyen || !clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiPhanQuyenMayChu))
                if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiPhanQuyenMayChu))
            {
                bbiPhanQuyenMayChu.Visibility = BarItemVisibility.Never;
            }

            //if (BienTc.isThanhPho || BienTc.isQuanHuyen || !clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiNhatKyChuyenDL))
                if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiNhatKyChuyenDL))
            {
                bbiNhatKyChuyenDL.Visibility = BarItemVisibility.Never;
            }

            rpgXuLy.Visible = bbiCauHinhMayChu.Visibility != BarItemVisibility.Never
                || bbiPhanQuyenMayChu.Visibility != BarItemVisibility.Never|| bbiNhatKyChuyenDL.Visibility != BarItemVisibility.Never;
            #endregion


            #region rpgQuanTri
            //if (BienTc.isThanhPho || BienTc.isQuanHuyen || !clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiDoiMatKhau))
                if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiDoiMatKhau))
            {
                bbiDoiMatKhau.Visibility = BarItemVisibility.Never;
            }

            //if (BienTc.isThanhPho || BienTc.isQuanHuyen || !clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_QuanLyNguoiDung))
                if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_QuanLyNguoiDung))
            {
                bbiQuanLyNguoiDung.Visibility = BarItemVisibility.Never;
            }

            rpgQuanTri.Visible = bbiDoiMatKhau.Visibility != BarItemVisibility.Never
                || bbiQuanLyNguoiDung.Visibility != BarItemVisibility.Never;
            #endregion


            #region rpgBackupRestore
            //if (BienTc.isThanhPho || BienTc.isQuanHuyen || !clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiBackup))
                if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiBackup))
            {
                bbiBackup.Visibility = BarItemVisibility.Never;
            }

            //if (BienTc.isThanhPho || BienTc.isQuanHuyen || !clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiRestore))
                if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiRestore))
            {
                bbiRestore.Visibility = BarItemVisibility.Never;
            }

            rpgBackupRestore.Visible = bbiBackup.Visibility != BarItemVisibility.Never
                || bbiRestore.Visibility != BarItemVisibility.Never;
            #endregion


            #region rpgNhatKyQuy
            //if (BienTc.isThanhPho || BienTc.isQuanHuyen || !clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiNhatKyQuy))
                if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiNhatKyQuy))
            {
                bbiNhatKyQuy.Visibility = BarItemVisibility.Never;
            }
            rpgNhatKyQuy.Visible = bbiNhatKyQuy.Visibility != BarItemVisibility.Never;
            #endregion

            rpHeThong.Visible = rpgXuLy.Visible || rpgQuanTri.Visible || rpgBackupRestore.Visible || rpgNhatKyQuy.Visible;
            #endregion


            #region rpgDanhMucChung
            //if (BienTc.isThanhPho || BienTc.isQuanHuyen || !clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiHoiDong))
                if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiHoiDong))
            {
                bbiHoiDong.Visibility = BarItemVisibility.Never;
            }

            //if (BienTc.isThanhPho || BienTc.isQuanHuyen || !clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiDMDonVi))
                if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiDMDonVi))
            {
                bbiDMDonVi.Visibility = BarItemVisibility.Never;
            }

            //if (BienTc.isThanhPho || BienTc.isQuanHuyen || !clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiDMCanBo))
                if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiDMCanBo))
            {
                bbiDMCanBo.Visibility = BarItemVisibility.Never;
            }

            //if (BienTc.isThanhPho || BienTc.isQuanHuyen || !clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bsiDanhMucChung))
                if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bsiDanhMucChung))
            {
                bsiDanhMucChung.Visibility = BarItemVisibility.Never;
            }
            rpgDanhMucChung.Visible = bsiDanhMucChung.Visibility != BarItemVisibility.Never;
            rpgDanhMucChung.Visible = bbiHoiDong.Visibility != BarItemVisibility.Never
                || bbiDMDonVi.Visibility != BarItemVisibility.Never
                || bbiDMCanBo.Visibility != BarItemVisibility.Never
                || bsiDanhMucChung.Visibility != BarItemVisibility.Never;
            #endregion


            #region rpgDMHopDong
            //if (BienTc.isThanhPho || BienTc.isQuanHuyen || !clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiDMHopDong))
                if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiDMHopDong))
            {
                bbiDMHopDong.Visibility = BarItemVisibility.Never;
            }

            //if (BienTc.isThanhPho || BienTc.isQuanHuyen || !clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiBaoCaoBienDong))
                if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiBaoCaoBienDong))
            {
                bbiBaoCaoBienDong.Visibility = BarItemVisibility.Never;
            }

            rpgDMHopDong.Visible = (bbiDMHopDong.Visibility != BarItemVisibility.Never
                || bbiBaoCaoBienDong.Visibility != BarItemVisibility.Never);
            
            #endregion


            #region HOA HỒNG
            #region rpgNhapDoanhThuDaiLy
            //if (BienTc.isThanhPho || BienTc.isQuanHuyen || !clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiNhapDoanhThuDaiLy))
                if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiNhapDoanhThuDaiLy))
            {
                bbiNhapDoanhThuDaiLy.Visibility = BarItemVisibility.Never;
            }

            rpgNhapDoanhThuDaiLy.Visible = bbiNhapDoanhThuDaiLy.Visibility != BarItemVisibility.Never;
            #endregion


            #region rpgBaoCaoDoanhThu
            //if (BienTc.isThanhPho || BienTc.isQuanHuyen || !clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiTongHopDT))
                if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiTongHopDT))
            {
                bbiTongHopDT.Visibility = BarItemVisibility.Never;
            }

            //if (BienTc.isQuanHuyen || !clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiTongHopDLyLuuDong))
                if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiTongHopDLyLuuDong))
            {
                bbiTongHopDLyLuuDong.Visibility = BarItemVisibility.Never;
            }

            rpgBaoCaoDoanhThu.Visible = bbiTongHopDLyLuuDong.Visibility != BarItemVisibility.Never
                || bbiTongHopDT.Visibility != BarItemVisibility.Never;
            #endregion

            rpHoaHong.Visible = rpgNhapDoanhThuDaiLy.Visible || rpgBaoCaoDoanhThu.Visible;
            #endregion HOA HỒNG


            #region TRUYỀN THỐNG
            //if (BienTc.isThanhPho || BienTc.isQuanHuyen || !clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiNhapVeNhan))
                if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiNhapVeNhan))
            {
                bbiNhapVeNhan.Visibility = BarItemVisibility.Never;
            }
            // fix
            //if (BienTc.isThanhPho || BienTc.isQuanHuyen || !clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiNhapVeHuy))
                if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiNhapVeHuy))
            {
                bbiNhapVeHuy.Visibility = BarItemVisibility.Never;
            }

            //if (BienTc.isThanhPho || BienTc.isQuanHuyen || !clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiBaoCaoThanhToan))
                if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiBaoCaoThanhToan))
            {
                bbiBaoCaoThanhToan.Visibility = BarItemVisibility.Never;
            }

            rpTruyenThong.Visible = (bbiNhapVeNhan.Visibility != BarItemVisibility.Never 
               || bbiNhapVeHuy.Visibility != BarItemVisibility.Never
                || bbiBaoCaoThanhToan.Visibility != BarItemVisibility.Never);
            #endregion rpTruyenThong

            #region LÔ TÔ

            if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiNhapSoDuThuong))
            {
               bbiNhapSoDuThuong.Visibility=BarItemVisibility.Never; 
            }
            if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiXemtheomay))
            {
                bbiXemtheomay.Visibility = BarItemVisibility.Never;
            }
            if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiXoaSDT1))
            {
                bbiXoaSDT1.Visibility = BarItemVisibility.Never;
            }
            if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_btnRutthuong))
            {
                btnRutthuong.Visibility = BarItemVisibility.Never;
            }
            if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiInTongHopDoanhThu))
            {
                bbiInTongHopDoanhThu.Visibility = BarItemVisibility.Never;
            }
            if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiInDT234))
            {
                bbiInDT234.Visibility = BarItemVisibility.Never;
            }
            if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bsiHoidong))
            {
                bsiHoidong.Visibility = BarItemVisibility.Never;
            }
            if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bsiBaocaoTH))
            {
                bsiBaocaoTH.Visibility = BarItemVisibility.Never;
            }
            rpLoTo.Visible = (bbiNhapSoDuThuong.Visibility != BarItemVisibility.Never
                              || bbiXemtheomay.Visibility != BarItemVisibility.Never
                              || bbiXoaSDT1.Visibility!=BarItemVisibility.Never
                              || btnRutthuong.Visibility!=BarItemVisibility.Never
                              || bbiInTongHopDoanhThu.Visibility!=BarItemVisibility.Never
                              || bbiInDT234.Visibility!=BarItemVisibility.Never
                              || bsiHoidong.Visibility!=BarItemVisibility.Never
                              || bsiBaocaoTH.Visibility!=BarItemVisibility.Never);
           
            #endregion rpLoTo
            #region Vé Bóc
            if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiVeboc))
            {
                bbiVeboc.Visibility = BarItemVisibility.Never;
            }
            if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_bbiInboc))
            {
               bbiInboc.Visibility = BarItemVisibility.Never;
            }rpVeboc.Visible = (bbiVeboc.Visibility != BarItemVisibility.Never
                               || bbiInboc.Visibility != BarItemVisibility.Never);
            #endregion rpVeboc
            #region Thế chấp
            //if (BienTc.isThanhPho || BienTc.isQuanHuyen || !clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_rpgTienTheChap))
                if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_rpgTienTheChap))
            {
                rpgTienTheChap.Visible = false;
            }

            //if (BienTc.isThanhPho || BienTc.isQuanHuyen || !clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_rpgBangTheoDoiDLTC))
                if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_rpgBangTheoDoiDLTC))
            {
                rpgBangTheoDoiDLTC.Visible = false;
            }

            //if (BienTc.isThanhPho || BienTc.isQuanHuyen || !clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_rpgDSDaiLyTheChap))
                if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_rpgDSDaiLyTheChap))
            {
                rpgDSDaiLyTheChap.Visible = false;
            }

            //if (BienTc.isThanhPho || BienTc.isQuanHuyen || !clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_rpgThietLapLaiXuat))
                if (!clsCommon.hasPermission(BienTc.UserID, (int)BienTc.eFunction.M_rpgThietLapLaiXuat))
            {
                rpgThietLapLaiXuat.Visible = false;
            }
            
            rpHopDong.Visible = (rpgDanhMucChung.Visible != false || rpgDMHopDong.Visible != false || rpgHopdongC1.Visible != false);
            
        }
            #endregion
        #endregion ===================================================================


        #region Control's event ======================================================
        private void barButtonItem1_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmHoaHongCFG frm = new frmHoaHongCFG();
            if (clsCommon.formIsNotExisting(frm.Name))
                frm.Show();
            else frm.Dispose();
        }

        private void barButtonItem2_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmDMDonVi frm = new frmDMDonVi();
            if (clsCommon.formIsNotExisting(frm.Name))
            {
                frm.MdiParent = this;
                frm.WindowState = FormWindowState.Maximized;
                frm.Show();
            }
            else frm.Dispose();
        }

        private void bbiDMChucVu_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmDMchung frm = new frmDMchung("DMCHUCVU");
            if (clsCommon.formIsNotExisting(frm.Name))
                frm.Show();
            else frm.Dispose();
        }

        private void barButtonItem4_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmDSLoaiHopDong frm = new frmDSLoaiHopDong();
            if (clsCommon.formIsNotExisting(frm.Name))
                frm.Show();
            else frm.Dispose();
        }

        private void barButtonItem5_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmDMchung frm = new frmDMchung("DMLYDOTHANHLY");
            if (clsCommon.formIsNotExisting(frm.Name))
                frm.Show();
            else frm.Dispose();
        }

        private void barButtonItem7_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmDMchung frm = new frmDMchung("DMTINHTRANG");
            if (clsCommon.formIsNotExisting(frm.Name))
                frm.Show();
            else frm.Dispose();
        }

        private void barButtonItem8_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmDMchung frm = new frmDMchung("DMLOAIVE");
            if (clsCommon.formIsNotExisting(frm.Name))
                frm.Show();
            else frm.Dispose();
        }

        private void barButtonItem9_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmChangePass frm = new frmChangePass();
            if (clsCommon.formIsNotExisting(frm.Name))
                frm.Show();
            else frm.Dispose();
        }

        private void bbiUserManage_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmQuanTriNguoiDung frm = new frmQuanTriNguoiDung();
            if (clsCommon.formIsNotExisting(frm.Name))
                frm.Show();
            else frm.Dispose();
        }

        private void barButtonItem13_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmDSHopDong frm = new frmDSHopDong();
            if (clsCommon.formIsNotExisting(frm.Name))
                frm.Show();
            else frm.Dispose();
        }

        private void barButtonItem14_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmHDong frm = new frmHDong();
            if (clsCommon.formIsNotExisting(frm.Name))
                frm.Show();
            else frm.Dispose();
        }

        private void barButtonItem16_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmThongtin frm = new frmThongtin();
            if (clsCommon.formIsNotExisting(frm.Name))
                frm.ShowDialog();
            else frm.Dispose();
        }

        private void barButtonItem18_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmBienDongDlyCap2 frm = new frmBienDongDlyCap2("CongTy");
            if (clsCommon.formIsNotExisting(frm.Name))
                frm.ShowDialog();
            else frm.Dispose();
        }

        private void bbiCauHinhMayChu_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmServerCfg frm = new frmServerCfg();
            if (clsCommon.formIsNotExisting(frm.Name))
                frm.ShowDialog();
            else frm.Dispose();
        }

        private void bbiPhanQuyenMayChu_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmPhanQuyenMay frm = new frmPhanQuyenMay();
            frm.ShowDialog();
        }

        private void bbiHoiDong_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmHoiDong frm = new frmHoiDong();
            if (clsCommon.formIsNotExisting(frm.Name))
            {
                frm.MdiParent = this;
                frm.WindowState = FormWindowState.Maximized;
                frm.Show();
            }
            else frm.Dispose();
        }

        private void bbiDMCanBo_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmDMCanBo frm = new frmDMCanBo();
            if (clsCommon.formIsNotExisting(frm.Name))
            {
                frm.MdiParent = this;
                frm.WindowState = FormWindowState.Maximized;
                frm.Show();
            }
            else frm.Dispose();
        }

        private void barButtonItem28_ItemClick(object sender, ItemClickEventArgs e)
        {
            //frmInDoanhThu234SovaCapso frm = new frmInDoanhThu234SovaCapso();
            //frm.ShowDialog();
        }

        private void barButtonItem27_ItemClick(object sender, ItemClickEventArgs e)
        {
        //    frmInBaocaoTH frm = new frmInBaocaoTH();
        //    frm.ShowDialog();
        }

        private void barButtonItem31_ItemClick_1(object sender, ItemClickEventArgs e)
        {
            frmNhatKyChuyenDL frm = new frmNhatKyChuyenDL();
            frm.ShowDialog();
        }
        #endregion ===================================================================


        #region Backup & Restore ======================================================
        private void bbiBackup_ItemClick(object sender, ItemClickEventArgs e)
        {
            SqlConnection conn = new SqlConnection(BienTc.connString);
            conn.Open();

            SaveFileDialog sfd = new SaveFileDialog();
            sfd.FileOk += new CancelEventHandler(sfd_FileOk);

            sfd.Title = "Sao lưu dữ liệu";
            sfd.Filter = "Tệp sao lưu (*.bak)|*.bak| Tất cả các tệp (*.*)|*.*";
            sfd.FileName = conn.Database + DateTime.Now.ToString("_yyyyMMdd_hhmmss");
            sfd.ValidateNames = true;
            sfd.OverwritePrompt = false;
            sfd.ShowDialog();
        }

        private void sfd_FileOk(object sender, CancelEventArgs e)
        {
            string file = ((SaveFileDialog)sender).FileName.Trim(new char[] { ' ', 'b', 'a', 'k', '.' });
            if (file.LastIndexOf('\\') == file.Length - 1)
            {
                clsCommon.MsgBox("Tên tệp không được để trống, vui lòng thử lại!", 5);
                e.Cancel = true;
            }
            else if (System.IO.File.Exists(file + ".bak"))
            {
                int startIndex = file.LastIndexOf('\\') + 1;
                string name = file.Substring(startIndex, file.Length - startIndex);
                if (clsCommon.MsgBox("Tệp " + name + ".bak đã tồn tại rồi. \nBạn có muốn thay thế nó không?", 4) != DialogResult.Yes)
                    e.Cancel = true;
                else
                    System.IO.File.Delete(file + ".bak");
            }

            //Thực hiện backup
            if (!e.Cancel)
            {
                SplashScreenManager.ShowForm(typeof(frmWaitForm));
                try
                {
                    clsDatabase cls = new clsDatabase();
                    cls.OnMyPercentComplete += new clsDatabase.MyPercentCompleteEventHandler((percent) => {});
                    cls.onOtherException += new clsDatabase.OnErrorHandler((exception) => { });
                    if (cls.backupKQXS(file + ".bak"))
                        clsCommon.MsgBox("Sao lưu dữ liệu thành công", 1);
                }
                catch (Exception ex)
                {
                    throw;
                }
                finally
                {
                    SplashScreenManager.CloseForm();
                }
            }
        }

        private void bbiRestore_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmRestore frm = new frmRestore();
            if (clsCommon.formIsNotExisting(frm.Name))
            {
                frm.StartPosition = FormStartPosition.CenterScreen;
                frm.ShowDialog();
            }
            else frm.Dispose();
        }
        #endregion Backup & Restore ===================================================

        private void bbiVeboc_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmInboc5 frm = new frmInboc5();
            frm.ShowDialog();
        }

        private void bbiInboc_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmInbocph5 frm = new frmInbocph5();
            frm.ShowDialog();
        }      
   }
}